package com.cade.agriculturemall.view.shoppingCar;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.ItemFavouriteEntity;
import com.cade.agriculturemall.model.ShopcarsModel;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.model.UserInfoEntity;
import com.cade.agriculturemall.widget.AmountView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lobby on 2017/12/14.
 */

public class ShopCarsExpandableListAdapter extends BaseExpandableListAdapter {
    private ExpandableListView vList;
    private Context context;
    private List<ShopcarsModel> list = new ArrayList<>();
    private AmountView mAmountView;
    private ShoppingCarFragment fragment;
    private MyClickListener myClickListener;

    public interface MyClickListener {
        public void clickListener(View v);
    }

    AVQuery<ShoppingCarsEntity> shoppingCarsEntityAVQuery = new AVQuery<>("ShoppingCars");

    public List<ShopcarsModel> getList() {
        return list;
    }

    public void setList(List<ShopcarsModel> list) {
        this.list = list;
    }

    public ShopCarsExpandableListAdapter(ShoppingCarFragment fragment, Context context, ExpandableListView vList,
                                         MyClickListener listener) {
        this.fragment = fragment;
        this.context = context;
        this.vList = vList;
        myClickListener = listener;
    }

    @Override
    public int getGroupCount() {
        return list.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return list.get(groupPosition).getGoodBeanList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return list.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return list.get(groupPosition).getGoodBeanList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_shopingcargroup, parent, false);
            holder = new GroupViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (GroupViewHolder) convertView.getTag();
        }
        holder.cbGroupItem.setTag(groupPosition);
        holder.cbGroupItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int section = (int) v.getTag();
                boolean isChecked = ((CheckBox) v).isChecked();
                list.get(section).setAllSelect(isChecked);
                for (ShoppingCarsEntity entity : list.get(section).getGoodBeanList()) {
                    entity.setSelected(isChecked);
                }
                notifyDataSetChanged();
                checkAllSelectedStatus();
            }
        });
//        holder.cbGroupItem.setOnClickListener(listener);
        holder.tvPosition.setText(list.get(groupPosition).getShopId());
        if (list.get(groupPosition).isAllSelect()) {
            if (!holder.cbGroupItem.isChecked()) {
                holder.cbGroupItem.setChecked(true);
            }
        } else {
            holder.cbGroupItem.setChecked(false);
        }
        return convertView;
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            notifyDataSetChanged();
            super.handleMessage(msg);
        }
    };

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_shopingcarchild, parent, false);
            holder = new ChildViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ChildViewHolder) convertView.getTag();
        }
        holder.cbItem.setTag(childPosition);
        holder.amountView.setTag(childPosition);
        holder.tvCount.setTag(childPosition);
//        holder.cbItem.setOnClickListener(listener);
        holder.tvDelelte.setTag(R.id.section, groupPosition);
        holder.tvDelelte.setTag(R.id.position, childPosition);
        holder.tvDelelte.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int section = (int) v.getTag(R.id.section);
                int position = (int) v.getTag(R.id.position);
                String objectId = list.get(section).getGoodBeanList().get(position).getObjectId();
                deleteShopCars(objectId, section, position);

            }
        });
        convertView.setTag(R.id.section, groupPosition);
        convertView.setTag(R.id.position, childPosition);
        convertView.setOnClickListener(childOnClickListener);
        holder.tvCollect.setTag(R.id.section, groupPosition);
        holder.tvCollect.setTag(R.id.position, childPosition);
        holder.tvCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int section = (int) v.getTag(R.id.section);
                int position = (int) v.getTag(R.id.position);
                String goodID = list.get(section).getGoodBeanList().get(position).getProId().getObjectId();
                String shopCarId = list.get(section).getGoodBeanList().get(position).getObjectId();
                Toast.makeText(context, "addFavourite", Toast.LENGTH_SHORT).show();
                addFavourite(goodID, shopCarId, section, position);
            }
        });
        holder.cbItem.setTag(R.id.section, groupPosition);
        holder.cbItem.setTag(R.id.position, childPosition);
        holder.cbItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int section = (int) v.getTag(R.id.section);
                int position = (int) v.getTag(R.id.position);
                boolean isChecked = ((CheckBox) v).isChecked();
                list.get(section).getGoodBeanList().get(position).setSelected(isChecked);
                boolean isCheck = true;
                for (ShoppingCarsEntity e : list.get(section).getGoodBeanList()) {
                    isCheck = e.isSelected();
                    if (!isCheck) {
                        break;
                    }
                }
                list.get(section).setAllSelect(isCheck);
                notifyDataSetChanged();
                checkAllSelectedStatus();
            }
        });
        if (list.get(groupPosition).getGoodBeanList().get(childPosition).isSelected()) {
            holder.cbItem.setChecked(true);
        } else {
            holder.cbItem.setChecked(false);
        }
        if (list.get(groupPosition).getGoodBeanList().get(childPosition).isedit()) {
            holder.amountView.setVisibility(View.VISIBLE);
        } else {
            holder.amountView.setVisibility(View.GONE);
        }
        holder.tvCount.setText("*" + list.get(groupPosition).getGoodBeanList().get(childPosition).getQuantitate() + "");
        holder.tvGoodName.setText(list.get(groupPosition).getGoodBeanList().get(childPosition).getProId().getTitle());
        if(list.get(groupPosition).getGoodBeanList().get(childPosition).getProId().getPicture().size()!=0) {
        Glide.with(context).load(list.get(groupPosition).getGoodBeanList().get(childPosition).getProId().getPicture().get(1)).into(holder.imageView);
        }

        holder.tvPrice.setText("￥" + list.get(groupPosition).getGoodBeanList().get(childPosition).getProId().getPriceNew() + "");
//        // 加减数量
        mAmountView = (AmountView) convertView.findViewById(R.id.amount_view);
        mAmountView.setOnAmountChangeListener(null);
        mAmountView.setTag(R.id.section, groupPosition);
        mAmountView.setTag(R.id.position, childPosition);
        mAmountView.setGoods_storage(50);
        mAmountView.setAmount(list.get(groupPosition).getGoodBeanList().get(childPosition).getQuantitate());

        mAmountView.setOnAmountChangeListener(onAmountChangeListener);
        return convertView;
    }


    private AmountView.OnAmountChangeListener onAmountChangeListener = new AmountView.OnAmountChangeListener() {
        @Override
        public void onAmountChange(View view, int amount) {
            int groupPosition = (int) view.getTag(R.id.section);
            int childPosition = (int) view.getTag(R.id.position);

            list.get(groupPosition).getGoodBeanList().get(childPosition).setQuantitate(amount);
            String objectId = list.get(groupPosition).getGoodBeanList().get(childPosition).getObjectId();
            upLoadQuantitate(objectId, amount);
            notifyDataSetChanged();
            myClickListener.clickListener(view);
//                fragment.countPrice();
//                notifyDataSetChanged();
        }
    };

    private View.OnClickListener childOnClickListener;

    public void setChildOnClickListener(View.OnClickListener childOnClickListener) {
        this.childOnClickListener = childOnClickListener;
    }

    /**
     * 删除
     *
     * @param shopCarId
     */
    public void deleteShopCars(String shopCarId, final int section, final int position) {
        shoppingCarsEntityAVQuery.whereEqualTo("objectId", shopCarId);
        shoppingCarsEntityAVQuery.deleteAllInBackground(new DeleteCallback() {
            @Override
            public void done(AVException e) {
                if (e == null)
                    handler.sendEmptyMessage(1);
                vList.collapseGroup(section);
                vList.expandGroup(section);
                list.remove(list.get(section).getGoodBeanList().get(position));
                onItemPlayClick.onItemClick(position);
            }
        });
        notifyDataSetChanged();
    }

    /**
     * 更新数量
     * LeanStorage 上的更新对象都是针对单个对象，云端会根据有没有 objectId 来决定是新增还是更新一个对象。
     * 更新操作是覆盖式的，云端会根据最后一次提交到服务器的有效请求来更新数据。更新是字段级别的操作，未更新的字段不会产生变动，这一点请不用担心
     *
     * @param shopCarId
     * @param Quantitate
     */
    public void upLoadQuantitate(String shopCarId, int Quantitate) {
        AVObject avObject = AVObject.createWithoutData("ShoppingCars", shopCarId);
        avObject.put("quantitate", Quantitate);
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
            }
        });
    }

    /**
     * 移至购物车
     * 需要先判断是否存在购物车
     *
     * @return
     */
    public void addFavourite(final String goodID, final String shopCarId, final int section, final int position) {
        AVQuery<GoodsDetailEntity> avQuery = new AVQuery<>("ClassifyGoodsThird");
        avQuery.whereEqualTo("objectId", goodID);
        avQuery.getFirstInBackground(new GetCallback<GoodsDetailEntity>() {
            @Override
            public void done(GoodsDetailEntity goodsDetailEntity, AVException e) {
                if (e == null) {
                    getGoodEntity(goodsDetailEntity, goodID, shopCarId, section, position);
                    // 存储成功
                } else {
                    // 失败的话，请检查网络环境以及 SDK 配置是否正确
                    e.printStackTrace();
                }
            }
        });
    }

    //      查看是是否存在收藏表
    public void getGoodEntity(final GoodsDetailEntity goodsDetailEntity, String goodID, final String shopCarId, final int section, final int position) {
        AVUser.alwaysUseSubUserClass(UserInfoEntity.class);
        final UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
        final String currentUserId = user.getObjectId();

        final AVQuery<ItemFavouriteEntity> itemEntity = new AVQuery<>("ItemFavourite");
        itemEntity.whereEqualTo("user_Id", currentUserId);
        itemEntity.whereEqualTo("pro_Id", goodID);
        itemEntity.findInBackground(new FindCallback<ItemFavouriteEntity>() {
            @Override
            public void done(List<ItemFavouriteEntity> list, AVException e) {
                if (e == null) {
//                    list.size=0 : 未收藏
                    if (list.size() == 0) {
                        Toast.makeText(context, "未存在于收藏表", Toast.LENGTH_SHORT).show();
                        addToCollect(currentUserId, goodsDetailEntity, shopCarId, section, position);

                    } else {
                        Toast.makeText(context, "已存在于收藏表", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }


    //    添加至收藏
    public void addToCollect(String currentUserId, GoodsDetailEntity entity, final String shopCarId, final int section, final int position) {
        final AVObject itemFavourite = new AVObject("ItemFavourite");
        itemFavourite.put("user_Id", currentUserId);
        itemFavourite.put("pro_Id", entity);
        itemFavourite.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    String itemFavouriteId = itemFavourite.getObjectId();
                    Toast.makeText(context, "收藏完成" + itemFavouriteId, Toast.LENGTH_SHORT).show();
                    deleteShopCars(shopCarId, section, position);
                }
            }
        });
    }

    /**
     * ExpandableListView 如果子条目需要响应click事件,必需返回true
     */
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    static class GroupViewHolder {
        CheckBox cbGroupItem;
        TextView tvPosition;

        public GroupViewHolder(View convertView) {
            cbGroupItem = (CheckBox) convertView.findViewById(R.id.cb_GroupItem);
            tvPosition = (TextView) convertView.findViewById(R.id.tv_Position);
        }
    }

    static class ChildViewHolder {
        CheckBox cbItem;
        ImageView imageView;
        LinearLayout linearLayout;
        TextView tvGoodName;
        TextView tvLimitCount;
        AmountView amountView;
        TextView tvPrice;
        TextView tvCount;
        TextView tvDelelte;
        TextView tvCollect;

        public ChildViewHolder(View convertView) {
            cbItem = (CheckBox) convertView.findViewById(R.id.cb_Item);
            imageView = (ImageView) convertView.findViewById(R.id.cb_image);
            linearLayout = (LinearLayout) convertView.findViewById(R.id.ll_Nomal);
            tvGoodName = (TextView) convertView.findViewById(R.id.tv_GoodName);
            amountView = (AmountView) convertView.findViewById(R.id.amount_view);
            tvPrice = (TextView) convertView.findViewById(R.id.tv_Price);
            tvCount = (TextView) convertView.findViewById(R.id.tv_Count);
            tvDelelte = (TextView) convertView.findViewById(R.id.shopping_car_tv_delete);
            tvCollect = (TextView) convertView.findViewById(R.id.shopping_car_tv_collect);
        }
    }

    private void checkAllSelectedStatus() {
        boolean isAllSelected = true;
        for (ShopcarsModel model : list) {
            if (!model.isAllSelect()) {
                isAllSelected = false;
                break;
            }
            for (ShoppingCarsEntity e : model.getGoodBeanList()) {
                if (!e.isSelected()) {
                    isAllSelected = false;
                    break;
                }
            }
        }
        if (isAllSelectedListener != null) {
            isAllSelectedListener.onSelectedChanged(isAllSelected);
        }
    }

    public interface IsAllSelectedListener {
        void onSelectedChanged(Boolean allSelected);
    }

    private IsAllSelectedListener isAllSelectedListener;

    public void setIsAllSelectedListener(IsAllSelectedListener isAllSelectedListener) {
        this.isAllSelectedListener = isAllSelectedListener;
    }


    public static interface OnItemDeleteListener { // true add; false cancel
        public void onItemClick(int position);
    } // add click callback

    OnItemDeleteListener onItemPlayClick;

    public void setOnPlayClickListener(OnItemDeleteListener onItemPlayClick) {
        this.onItemPlayClick = onItemPlayClick;
    }
}
